package com.example.sinoyd.frameapplication.ProjectCodes.UI

import android.os.Bundle
import android.os.Looper
import com.example.sinoyd.frameapplication.KotlinFrame.Dataclass.gson
import com.example.sinoyd.frameapplication.KotlinFrame.Frame.Uitl.Networkrequestmodel
import com.example.sinoyd.frameapplication.KotlinFrame.UI.BaseActivity
import com.example.sinoyd.frameapplication.ProjectCodes.Dataclass.GetLoginInfo
import com.example.sinoyd.frameapplication.R
import com.sinoyd.Code.Until.Networkrequestaddress
import com.sinoyd.Code.Until.SharedPreferencesFactory
import com.sinoyd.Code.Until.showdialog
import kotlinx.android.synthetic.main.activity_login.*
import okhttp3.Response
import org.jetbrains.anko.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.net.URLEncoder

class LoginActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        setlisteners()
    }

    private fun setlisteners() {

        login_btn.onClick {
            when {
                user_name_edit.text.toString() == "" -> toast("请输入用户名")
                user_pass_edit.text.toString() == "" -> toast("请数据密码")
                else -> //登陆
                    GetLoginInfo(user_name_edit.text.toString(), user_pass_edit.text.toString())
            }

        }

    }


    //登陆请求
    fun GetLoginInfo(username: String, password: String) {
        showdialog("loadshow")
        var ntrequest = Networkrequestmodel()
        ntrequest.setMethod(Networkrequestmodel.GETREQUEST)
                .settag("GetLoginInfo")
                .seturl(Networkrequestaddress.URL_GetLoginInfo)
                .addparam("loginId", username)
                .addparam("pwd", URLEncoder.encode(password))
                .start(this)
    }

    var getLoginInfo: GetLoginInfo = com.example.sinoyd.frameapplication.ProjectCodes.Dataclass.GetLoginInfo()
    override fun requestSuccess(response: Response, TAG: String) {
        super.requestSuccess(response, TAG)
        when (TAG) {
            "GetLoginInfo" -> {
                getLoginInfo = gson.fromJson(responsestr, GetLoginInfo::class.java)
                if (getLoginInfo.login == "True") {
                    SharedPreferencesFactory.savedata(this, "username", user_name_edit.text.toString())
                    SharedPreferencesFactory.savedata(this, "password", user_pass_edit.text.toString())
                    startActivity<OsChooseActivity>()
                    finish()
                } else {
                    Looper.prepare()
                    toast("登陆失败")
                    Looper.loop()
                }
            }
        }
    }
}
